<template>
  <div class="upload-container">
    <el-button style="background:#1890ff,borderColor:#1890ff" icon="el-icon-upload" size="mini" type="primary" @click="openDialog">上传图片</el-button>
    <CopImgMaterial ref="pics" :max="99999" @getUrl="getPicsUrl" />
    <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="false" :modal="false">
      <el-upload
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        :http-request="uploadBefore"
        class="editor-slide-upload"
        action=""
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <div>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CopImgMaterial from '@/components/copSource/img'
import axios from 'axios'
import { getPolicy } from '@/api/common'
import { uploadImageTextMediaToWx } from '@/api/wxMp'

export default {
  components: {
    CopImgMaterial
  },
  props: {
    type: {
      type: String,
      required: false,
      default: () => ''
    },
    tinymceinfo: {
      type: Object,
      required: false,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogVisible: false,
      listObj: {},
      fileList: [],
      info: {
        name: '',
        key: '',
        policy: '',
        OSSAccessKeyId: '',
        success_action_status: '',
        callback: '',
        signature: ''
      }
    }
  },
  created() {},
  methods: {
    getPicsUrl(arr) {
      const obj = {}
      arr.forEach((item, index) => {
        obj[index] = { uid: index, url: item }
      })
      const arr1 = Object.keys(obj).map(v => obj[v])
      this.$emit('successCBK', arr1)
    },
    openDialog() {
      if (this.type === 'goods') {
        this.$refs.pics.dialog = true
        return false
      }
      this.dialogVisible = true
    },
    beforeUpload(file) {
      if (file.type.split('/')[0] !== 'image') {
        this.$message.error('上传图片格式不正确')
        return false
      }
    },
    uploadBefore(file) {
      getPolicy({}, 'get').then(res => {
        const formData = new FormData()
        const name = res.dir + file.file.name.split('.')[0] + '_' + new Date().getTime() + '.' + file.file.name.split('.')[1]
        formData.append('policy', res.policy)
        formData.append('OSSAccessKeyId', res.accessId)
        formData.append('success_action_status', '200')
        formData.append('signature', res.signature)
        formData.append('key', name)
        formData.append('file', file.file)
        formData.append('type', file.file.type)
        if (res.callback !== null) {
          formData.append('callback', res.callback)
        }
        const _self = this
        const _URL = window.URL || window.webkitURL
        const fileName = file.file.uid
        this.listObj[fileName] = {}
        return new Promise((resolve, reject) => {
          const img = new Image()
          img.src = _URL.createObjectURL(file.file)
          img.onload = function() {
            _self.listObj[fileName] = { uid: file.file.uid }
          }
          axios({
            url: res.host,
            method: 'POST',
            headers: { 'content-type': 'application/x-www-form-urlencoded' },
            data: formData
          }).then(() => {
            const uid = file.file.uid
            const objKeyArr = Object.keys(_self.listObj)
            const url = `${res.host}/${name}`
            if (this.tinymceinfo.appId === '' || this.tinymceinfo.appId === undefined) {
              for (let i = 0, len = objKeyArr.length; i < len; i++) {
                if (_self.listObj[objKeyArr[i]].uid === uid) {
                  _self.listObj[objKeyArr[i]].url = url
                  return
                }
              }
              _self.$message.success('上传成功')
            } else {
              uploadImageTextMediaToWx({ appId: this.tinymceinfo.appId, path: name }).then(res1 => {
                for (let i = 0, len = objKeyArr.length; i < len; i++) {
                  if (_self.listObj[objKeyArr[i]].uid === uid) {
                    _self.listObj[objKeyArr[i]].url = res1
                    return
                  }
                }
                _self.$message.success('上传成功')
              })
            }
          }).catch(err => {
            this.$message.error(err.msg)
          })
          resolve(true)
        })
      })
    },
    handleSubmit() {
      const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      this.$emit('successCBK', arr)
      this.listObj = {}
      this.fileList = []
      this.dialogVisible = false
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    }
  }
}
</script>

<style lang="scss" >
.upload-container{
  padding: .05rem .05rem 0 0;
  .editor-slide-upload {
    margin-bottom: 20px;
    .el-upload  {
      width: auto;
      padding: .5rem 0;
      box-sizing: border-box;
    }
    .el-dialog{
      .el-upload el-upload {
        margin-bottom: 10px;
      }
    }
  }
  .editor-slide-upload{
    overflow: hidden;
  }
  .el-dialog__header{
    overflow: hidden;
    margin-bottom: 10px;
  }
}
</style>
